package com.wuwei.elearning.utils.token;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuwei.elearning.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class TokenManager {

    // 微信公众号的AppID和AppSecret
    private static final String APP_ID = "wx1d7840ee01b77074";
    private static final String APP_SECRET = "60670d14c195ca669ed8f43ef295fa2e";

    // access_token有效期，默认为7200秒（2小时）
    private static int ACCESS_TOKEN_EXPIRES_IN = Integer.MAX_VALUE;

    // access_token的创建时间和过期时间
    private static Date accessTokenCreateTime;
    private static Date accessTokenExpiresTime;



    /**
     * 获取access_token
     */
    public static String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        String result = sendGet(url);
        JSONObject json = JSON.parseObject(result);
        boolean key = json.containsKey("access_token");
        if (key) {
            String accessToken = json.getString("access_token");
            Integer expiresIn = json.getInteger("expires_in");
            ACCESS_TOKEN_EXPIRES_IN = expiresIn;
            accessTokenCreateTime = new Date();
            accessTokenExpiresTime = new Date(accessTokenCreateTime.getTime() + ACCESS_TOKEN_EXPIRES_IN * 1000);
            return accessToken;
        } else {
            return null;
        }
    }

    /**
     * 获取access_token
     */
    public static Token getAccess_Token() throws Exception {
        Token newToken = new Token();
        String host = "https://api.weixin.qq.com";
        String path = "/cgi-bin/token";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        Map<String,String> querys = new HashMap<>();
        querys.put("grant_type", "client_credential");
        querys.put("appid",APP_ID);
        querys.put("secret",APP_SECRET);
        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        String responseBody = EntityUtils.toString(response.getEntity());
        JSONObject object = JSON.parseObject(responseBody);
        String token = object.getString("access_token");//获取到token
        Date accessTokenCreateTime = new Date();
        newToken.setToken(token);
        newToken.setAccessTokenCreateTime(accessTokenCreateTime);
        return newToken;
    }


    /**
     * 判断access_token是否过期
     */
    public static boolean isAccessTokenValid() {
        if (accessTokenCreateTime == null || accessTokenExpiresTime == null) {
            return false;
        }
        Date now = new Date();
        long timeDiff = accessTokenExpiresTime.getTime() - now.getTime();
        return timeDiff > 0;
    }

    /**
     * 发送HTTP GET请求
     */
    public static String sendGet(String url) throws IOException {
        URLConnection connection = new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        reader.close();
        inputStream.close();
        return result.toString();
    }

    public static boolean testToken(Date accessTokenCreateTime) throws Exception {
        Date accessTokenExpiresTime = new Date(accessTokenCreateTime.getTime() + ACCESS_TOKEN_EXPIRES_IN * 1000);
        Date now = new Date();
        long timeDiff = accessTokenExpiresTime.getTime() - now.getTime();
        return timeDiff > 0;
    }
}
